﻿using Microsoft.IdentityModel.Tokens;
using System.Text.Json;

namespace Soul.IdentityServer.Hosting
{
    public class SigningCredentialsBuilder
    {
        private readonly List<SigningCredentials> _signingCredentials = new List<SigningCredentials>();

        public SigningCredentialsBuilder()
        {

        }

        public SigningCredentialsBuilder AddSigningCredentials(SigningCredentials credential)
        {
            _signingCredentials.Add(credential);

            return this;
        }

        public SigningCredentialsBuilder AddDeveloperSigningCredentials(bool persistKey = true, string? filename = null, string signingAlgorithm = SecurityAlgorithms.RsaSha256)
        {
            if (filename == null)
            {
                filename = Path.Combine(Directory.GetCurrentDirectory(), "idsvr.jwk");
            }
            if (File.Exists(filename))
            {
                var json = File.ReadAllText(filename);
                var jwk = new JsonWebKey(json);
                AddSigningCredentials(new SigningCredentials(jwk, signingAlgorithm));
                return this;
            }
            else
            {
                var rsaSecurityKey = CryptoUtility.CreateRsaSecurityKey();
                var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(rsaSecurityKey);
                jwk.Alg = signingAlgorithm.ToString();
                if (persistKey)
                {
                    File.WriteAllText(filename, JsonSerializer.Serialize(jwk));
                }
                AddSigningCredentials(new SigningCredentials(jwk, signingAlgorithm));
                return this;
            }
        }

        internal List<SigningCredentials> Build()
        {
            return _signingCredentials;
        }
    }
}
